package com.coffee.monitor.mina;

import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description: 单例工具类，保存所有mina客户端连接
 * @author coffee
 *
 */
public class SessionMap {
	
	private final static Logger log = LoggerFactory.getLogger(SessionMap.class);
	
	private static SessionMap sessionMap = null;
			
	private Map<Long, IoSession> map = new HashMap<Long, IoSession>();
	private Map<Long, Long> sessionId = new HashMap<Long, Long>();
	
	
	//构造私有化 单例
	private SessionMap(){}
	
	
	/**
	 * @Description: 获取唯一实例
	 * @author coffee
	 */
	public static SessionMap newInstance(){
		log.debug("SessionMap单例获取---");
		if(sessionMap == null){
			sessionMap = new SessionMap();
		}
		return sessionMap;
	}
	
	
	/**
	 * @Description: 保存session会话
	 * @author coffee
	 */
	public void addSession(Long key, IoSession session){
		log.debug("保存会话到SessionMap单例---key=" + key);
		this.map.put(key, session);
		this.sessionId.put(session.getId(), key);
	}
	
	/**
	 * @Description: 根据key查找缓存的session
	 * @author coffee
	 */
	public void remove(Long key,Long deviceId){
		log.debug("移除会话从SessionMap单例---key=" + key);
		this.map.remove(key);
		this.sessionId.remove(deviceId);
	}
	/**
	 * @Description: 根据key查找缓存的session
	 * @author coffee
	 */
	public IoSession getSession(Long key){
		log.debug("获取会话从SessionMap单例---key=" + key);
		return this.map.get(key);
	}
	/**
	 * @Description: 根据key查找缓存的deviceId
	 * @author coffee
	 */
	public Long getDeviceBySessionId(Long sessionId){
		log.debug("获取会话从SessionMap单例---sessionId=" + sessionId);
		Long key=this.sessionId.get(sessionId);
		if (key==null) {
			return null;
		}else{
			return key;
		}
	}
	/**
	 * @Description: 根据key查找缓存的session
	 * @author coffee
	 */
	public IoSession getSessionBySessionId(Long sessionId){
		log.debug("获取会话从SessionMap单例---sessionId=" + sessionId);
		Long key=this.sessionId.get(sessionId);
		if (key==null) {
			return null;
		}else{
			return this.map.get(key);
		}
	}
	
	/**
	 * @Description: 获取会话池中的数量
	 * @author coffee
	 */
	public int getSessionCount(){
		log.debug("获取会话池中的数量");
		return this.map.size();
	}
	/**
	 * @Description: 获取会话池中的数量
	 * @author coffee
	 */
	public int getDeviceCount(){
		log.debug("获取会话池中设备id的数量");
		return this.map.size();
	}
	
	/**
	 * @Description: 发送消息到客户端
	 * @author coffee
	 */
	public void sendMessage(Long[] keys, Object message){
		for(Long key : keys){
			IoSession session = getSession(key);
			
			log.debug("反向发送消息到客户端Session---key=" + key + "----------消息=" + message);
			if(session == null){
				return;
			}
			session.write(message);
			
		}
	}
	
	
	

}